package com.zggk.lzz.updata;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import com.alibaba.fastjson.JSON;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zggk.lzz.R;
import com.zggk.lzz.api.MyApplication;
import com.zggk.lzz.api.Urls;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 软件升级
 * @author shichenwei
 */

public class UpdateManager {
    private static final int DOWNLOAD = 1;
    private static final int DOWNLOAD_FINISH = 2;
    private String mSavePath;
    private int progress;
    private boolean cancelUpdate = false;
    private Context mContext;
    private HorizontalProgressBarWithNumber mProgress;
    private Dialog mDownloadDialog;
    private int currentVersionCode;
    private int serverVersionCode;
    private AppVersionBO appVersionBO;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD:
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    installApk();
                    break;
                default:
                    break;
            }
        }
    };

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    class UpdateThread extends Thread {
        public void run() {
            isUpdate();
        }
    }

    public void checkUpdate() {
        new UpdateThread().start();
    }

    private void isUpdate() {
        getVersionCode(mContext);
        OkGo.<String>post(Urls.JAVASERVER+"pms/rhms/lzzapp/getAppVersion")
                .params("appName", "路长制_android")
                .params("token", "Bearer$" + MyApplication.spUtils.getString("Token",""))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        AppVersionBO videoVos2 = JSON.parseObject(response.body(), AppVersionBO.class);
                        appVersionBO = videoVos2;
                        serverVersionCode = Integer.valueOf(appVersionBO.getDATA().get(0).getVersionCode());
                        if (serverVersionCode > currentVersionCode) {
                            showMustUpdateDialog();
                            return;
                        }
                    }
                });
    }

    private void getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            currentVersionCode = packInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void showMustUpdateDialog() {
        Builder builder = new Builder(mContext);
        builder.setTitle("软件更新");
        StringBuilder message = new StringBuilder();
        message.append("当前版本过低，必须升级才能继续使用！");
        builder.setMessage(message.toString());
        builder.setCancelable(false);
        builder.setPositiveButton("更新",
                new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDownloadDialog();
                    }
                });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    private void showDownloadDialog() {
        Builder builder = new Builder(mContext);
        builder.setTitle("软件更新");
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (HorizontalProgressBarWithNumber) v.findViewById(R.id.update_progress);
        builder.setView(v);
        builder.setCancelable(false);
        // 取消更新
        builder.setNegativeButton("取消",
                new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        cancelUpdate = true;
                    }
                });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        downloadApk();
    }

    private void downloadApk() {
        new downloadApkThread().start();
    }

    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    File sdDir = Environment.getExternalStorageDirectory();//获取跟目录
                    mSavePath = sdDir.toString() + "/rcyht";
                } else {
                    mSavePath = "/data/data/com.zggk.lzz/download";
                }
                URL url = new URL(appVersionBO.getDATA().get(0).getUrl());
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();
                File file = new File(mSavePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                File apkFile = new File(mSavePath, "lzz.apk");
                String[] command = {"chmod", "777", mSavePath + "/" + "lzz.apk"};
                String[] command2 = {"chmod", "777", mSavePath};
                ProcessBuilder builder = new ProcessBuilder(command);
                ProcessBuilder builder2 = new ProcessBuilder(command2);
                try {
                    builder.start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                FileOutputStream fos = new FileOutputStream(apkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    mHandler.sendEmptyMessage(DOWNLOAD);
                    if (numread <= 0) {
                        builder2.start();
                        mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!cancelUpdate);
                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mDownloadDialog.dismiss();
        }
    }

    private void installApk() {
        File apkfile = new File(mSavePath, "lzz.apk");
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mContext, "com.zggk.lzz.fileprovider", apkfile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (mContext.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            mContext.startActivity(intent);
        }
    }

}